package com.Principal;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.Principal.R;

import adaptar.Mensajes;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

@TargetApi(3)
public class MyCalendarActivity extends Activity implements OnClickListener {
	private static final String tag = "MyCalendarActivity";

	private TextView currentMonth;
	public static Button gridcell;
	private Button addEvent;
	//private static Button selectedDayMonthYearButton;
	private ImageView prevMonth;
	private ImageView nextMonth;
	public GridView calendarView;
	public static GridCellAdapter adapter;
	private Calendar _calendar;
	@SuppressLint("NewApi")
	public int day;
	public static int [] dias;
	public static int [] meses;
	public static int [] anios;
	public static String fechaSeleccionada;
	public static String diaSeleccionado;
    public static String mesSeleccionado;
    public static String añoSeleccionado;
    public static String mes="";
    
	@SuppressLint("NewApi")
	private int month;

	@SuppressLint("NewApi")
	private int year;
	@SuppressWarnings("unused")
	@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
	//private final DateFormat dateFormatter = new DateFormat();
	private static final String dateTemplate = "MMM yyyy";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_calendar_view);
		 		
		_calendar = Calendar.getInstance(TimeZone.getTimeZone("America/Argentina/Buenos_Aires"),new Locale("es"));
		month = _calendar.get(Calendar.MONTH) + 1;
		year = _calendar.get(Calendar.YEAR);
		
		Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: "
				+ year);

		/*selectedDayMonthYearButton = (Button) this
				.findViewById(R.id.selectedDayMonthYear);
		selectedDayMonthYearButton.setText("Selected: ");
		*/	
		
		//Boton que va a agregar un evento
		addEvent=(Button) this.findViewById(R.id.addEvent);
		addEvent.setOnClickListener(new OnClickListener() {
			//@Override
			//agregar evento
			public void onClick(View v) {
		    	
				}	
			
		});

		
		prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
		prevMonth.setOnClickListener(this);

		currentMonth = (TextView) this.findViewById(R.id.currentMonth);
		
		//setear mes en castellano
		mes="";
		if (month==1){
			mes="Enero ";
		}else if (month==2){
				mes="Febrero ";
		}else if (month==3){
			mes="Marzo ";
		}else if (month==4){
			mes="Abril ";
		}else if (month==5){
			mes="Mayo ";
		}else if (month==6){
			mes="Junio ";
		}else if (month==7){
			mes="Julio ";
		}else if (month==8){
			mes="Agosto ";
		}else if (month==9){
			mes="Septiembre ";
		}else if (month==10){
			mes="Octubre ";
		}else if (month==11){
			mes="Noviembre ";
		}else if (month==12){
			mes="Diciembre ";
		}
		//setear en el calendario el textviex donde aparece el mes y el año
		currentMonth.setText(mes+year);

		nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
		nextMonth.setOnClickListener(this);

		calendarView = (GridView) this.findViewById(R.id.calendar);


		// Initialised
		adapter = new GridCellAdapter(getApplicationContext(),
				R.id.calendar_day_gridcell, month, year,day);
		adapter.notifyDataSetChanged();
		calendarView.setAdapter(adapter);		
	
		
			}

	//setear arreglo que contiene los dias con noticias y los meses con meses de noticias
			public void setDiasMesAnio(int [] diasNot,int [] mesNot, int [] aniosNot){
			 dias=diasNot;
			 meses=mesNot;
			 anios=aniosNot;
			}
			
			
			
	

	/**
	 * 
	 * @param month
	 * @param year
	 * @param day
	 */
	
	
	public void setGridCellAdapterToDate(int month, int year,int day) {
		adapter = new GridCellAdapter(getApplicationContext(),
				R.id.calendar_day_gridcell, month, year,day);
		_calendar.set(day, month - 1, _calendar.get(Calendar.DAY_OF_MONTH));
		//setear mes en castellano
		if (month==1){
			mes="Enero ";
		}else if (month==2){
				mes="Febrero ";
		}else if (month==3){
			mes="Marzo ";
		}else if (month==4){
			mes="Abril ";
		}else if (month==5){
			mes="Mayo ";
		}else if (month==6){
			mes="Junio ";
		}else if (month==7){
			mes="Julio ";
		}else if (month==8){
			mes="Agosto ";
		}else if (month==9){
			mes="Septiembre ";
		}else if (month==10){
			mes="Octubre ";
		}else if (month==11){
			mes="Noviembre ";
		}else if (month==12){
			mes="Diciembre ";
		}
		//setear en el calendario el textviex donde aparece el mes y el año
		currentMonth.setText(mes+year);
		adapter.notifyDataSetChanged();
		calendarView.setAdapter(adapter);
	}
	
	@Override
	public void onClick(View v) {
		if (v == prevMonth) {
			if (month <= 1) {
				month = 12;
				year--;
			} else {
				month--;
			}
			Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month: "
					+ month + " Year: " + year);
			setGridCellAdapterToDate(month, year,day);
		}
		if (v == nextMonth) {
			if (month > 11) {
				month = 1;
				year++;
			} else {
				month++;
			}
			Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month: "
					+ month + " Year: " + year);
			setGridCellAdapterToDate(month, year,day);
			
		}

	}

	@Override
	public void onDestroy() {
		Log.d(tag, "Destroying View ...");
		super.onDestroy();
	}
	
	

	// Inner Class
	@SuppressLint("NewApi")
	public class GridCellAdapter extends BaseAdapter implements OnClickListener {
		private static final String tag = "GridCellAdapter";
		private final Context _context;

		private final List<String> list;
		private static final int DAY_OFFSET = 1;
		private final String[] weekdays = new String[] { "Sun", "Mon", "Tue",
				"Wed", "Thu", "Fri", "Sat" };
		private final String[] months = { "January", "February", "March",
				"April", "May", "June", "July", "August", "September",
				"October", "November", "December" };
		private final int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
				31, 30, 31 };
		private int daysInMonth;
		private int currentDayOfMonth;
		private int currentWeekDay;
		private Button gridcell;
		private TextView num_events_per_day;
		private final HashMap<String, Integer> eventsPerMonthMap;
		private final SimpleDateFormat dateFormatter = new SimpleDateFormat(
				"dd-MM-yyyy",new Locale ("es_ES"));
		String fecha=dateFormatter.format(new Date());
		
		

		// Days in Current Month
		public GridCellAdapter(Context context, int textViewResourceId,
				int month, int year, int day) {
			super();
			this._context = context;
			this.list = new ArrayList<String>();
			Log.d(tag, "==> Passed in Date FOR Month: " + month + " "
					+ "Year: " + year);
			Locale l = new Locale("es","AR");
			Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("America/Argentina/Buenos_Aires"),l);
			setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
			setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
			Log.d(tag, "New Calendar:= " + calendar.getTime().toString());
			Log.d(tag, "CurrentDayOfWeek :" + getCurrentWeekDay());
			Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());

			// Print Month
			printMonth(day,month, year);

			// Find Number of Events
			eventsPerMonthMap = findNumberOfEventsPerMonth(year, month);
			
			
		}

		private String getMonthAsString(int i) {
			return months[i];
		}

		private String getWeekDayAsString(int i) {
			return weekdays[i];
		}

		private int getNumberOfDaysOfMonth(int i) {
			return daysOfMonth[i];
		}

		public String getItem(int position) {
			return list.get(position);
		}

		@Override
		public int getCount() {
			return list.size();
		}
		
		//verifica si algun dia del calendario coincide con alguno en que hay noticias y me devuelve la posicion en el arreglo
		public int verificar(int x,int [] diass){
			int dia;
			int verificacion=-1;
			System.out.println("longitud"+diass.length);
			for(int y=0;y<diass.length;y++){
				dia = diass[y];
				if (x==dia){
				verificacion=y;
				}				
			}			
		return verificacion;	
		}

		//verifica que el mes de la noticia coincida con el mes actual, de lo contrario no se marca en el calendrio
		public boolean verificarMesYAnio(int x,int [] mes, int mesActual,int [] anios, int anioActual){
			boolean verific=false;
			if ((x != -1) && (mes[x] == mesActual) && anios[x]==anioActual){
				verific = true;
			}
			return verific;			
		}
		
	
			
		
		/**
		 * Prints Month
		 * 
		 * @param mm
		 * @param yy
		 */
			

		public void printMonth(int day,int mm, int yy) {
			Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy  + "dia " +day  );
			int trailingSpaces = 0;
			int daysInPrevMonth = 0;
			int prevMonth = 0;
			int prevYear = 0;
			int nextMonth = 0;
			int nextYear = 0;
            
			int currentMonth = mm - 1;
			String currentMonthName = getMonthAsString(currentMonth);
			//cantidad de dias que tiene el mes
			
			daysInMonth = getNumberOfDaysOfMonth(currentMonth);
			
			Log.d(tag, "Current Month: " + " " + currentMonthName + " having "
					+ daysInMonth + " days.");

			GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
			Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());

			if (currentMonth == 11) {
				prevMonth = currentMonth - 1;
				daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
				nextMonth = 0;
				prevYear = yy;
				nextYear = yy + 1;
				Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:"
						+ prevMonth + " NextMonth: " + nextMonth
						+ " NextYear: " + nextYear);
			} else if (currentMonth == 0) {
				prevMonth = 11;
				prevYear = yy - 1;
				nextYear = yy;
				daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
				nextMonth = 1;
				Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:"
						+ prevMonth + " NextMonth: " + nextMonth
						+ " NextYear: " + nextYear);
			} else {
				prevMonth = currentMonth - 1;
				nextMonth = currentMonth + 1;
				nextYear = yy;
				prevYear = yy;
				daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
				Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:"
						+ prevMonth + " NextMonth: " + nextMonth
						+ " NextYear: " + nextYear);
			}

			int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
			trailingSpaces = currentWeekDay;

			Log.d(tag, "Week Day:" + currentWeekDay + " is "
					+ getWeekDayAsString(currentWeekDay));
			Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
			Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);

			if (cal.isLeapYear(cal.get(Calendar.YEAR)))
				if (mm == 2)
					++daysInMonth;
				else if (mm == 3)
					++daysInPrevMonth;

			// Trailing Month days
			for (int i = 0; i < trailingSpaces; i++) {
				Log.d(tag,
						"PREV MONTH:= "
								+ prevMonth
								+ " => "
								+ getMonthAsString(prevMonth)
								+ " "
								+ String.valueOf((daysInPrevMonth
										- trailingSpaces + DAY_OFFSET)
										+ i));
				list.add(String
						.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET)
								+ i)
						+ "-GREY"
						+ "-"
						+ getMonthAsString(prevMonth)
						+ "-"
						+ prevYear);
			}
			
			

			
			// Current Month Days
			//coloca 0 donde no hay nada en el arreglo de dias de noticias, esto hay q sacarlo porq el arreglo de dias de noticias, solo tiene q tener la cantidad de elementos como noticias haya
				
			for (int i = 1; i <= daysInMonth; i++) {
				Log.d(currentMonthName, String.valueOf(i) + " "
						+ getMonthAsString(currentMonth) + " " + yy);
				if (i == getCurrentDayOfMonth()) {
					list.add(String.valueOf(i) + "-BLUE" + "-"
							+ getMonthAsString(currentMonth) + "-" + yy);
					}else {
						//verifica si hay alguna noticia de ese dia "i", entonces lo marca con naranja para luego mostrar en el calendario
						//solo se debe hacer esto si coincide con el mes de la noticia
						int mesActual = currentMonth+1;
						int añoActual = year;
						//verificar (i,dias) me devuelve la posicion en el arreglo donde el dia de la noticia coincide con el i, para luego ver si el mes coincide con el mes actual
						if (verificarMesYAnio(verificar(i,dias),meses,mesActual,anios,añoActual)|| i== getCurrentDayOfMonth()){
							list.add(String.valueOf(i) + "-orrange" + "-"
									+ getMonthAsString(currentMonth) + "-" + yy);
						}else{
							list.add(String.valueOf(i) + "-WHITE" + "-"
									+ getMonthAsString(currentMonth) + "-" + yy);
						}					
				}
			}
			


			// Leading Month days
			for (int i = 0; i < list.size() % 7; i++) {
				Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
				list.add(String.valueOf(i + 1) + "-GREY" + "-"
						+ getMonthAsString(nextMonth) + "-" + nextYear);
			}
		}
		

		public String IncluirDatos(String dato){
			return dato;
		}
	
		/**
		 
		 * 
		 * @param year
		 * @param month
		 * @return
		 */
		private HashMap<String, Integer> findNumberOfEventsPerMonth(int year,
				int month) {
			HashMap<String, Integer> map = new HashMap<String, Integer>();

			return map;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if (row == null) {
				LayoutInflater inflater = (LayoutInflater) _context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				row = inflater.inflate(R.layout.screen_gridcell, parent, false);
			}

			// Get a reference to the Day gridcell
			gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
			gridcell.setOnClickListener(this);
		
			// ACCOUNT FOR SPACING			
			Log.d(tag, "Current Day: " + getCurrentDayOfMonth());
			
			String[] day_color = list.get(position).split("-");
			//dias
			String theday = day_color[0];
			//day_color[1] aca estan los colores
			//meses
			String themonth = day_color[2];
			System.out.println("mm"+day_color[2]);
			String theyear = day_color[3];
			if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null)) {
				if (eventsPerMonthMap.containsKey(theday)) {
					num_events_per_day = (TextView) row
							.findViewById(R.id.num_events_per_day);
					Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
					num_events_per_day.setText(numEvents.toString());
				}
			}

			// Set the Day GridCell
			gridcell.setText(theday);
			gridcell.setTag(theday + "-" + themonth + "-" + theyear);
			Log.d(tag, "Setting GridCell " + theday + "-" + themonth + "-"
					+ theyear);
		

			if (day_color[1].equals("GREY")) {
				gridcell.setTextColor(gridcell.getResources()
						.getColor(R.color.lightgray));
			}
			if (day_color[1].equals("WHITE")) {
				gridcell.setTextColor(gridcell.getResources().getColor(
						R.color.lightgray02));
			}
			if (day_color[1].equals("BLUE")) {
				gridcell.setTextColor(gridcell.getResources().getColor(R.color.blue));
			}
			//agregado para ponerle el color del dia en donde se encontrara la noticia
			if (day_color[1].equals("orrange")){
				gridcell.setTextColor(gridcell.getResources().getColor(R.color.black));
			}
			return row;
		}
		
		public void onClick(View view) {
			String date_month_year = (String) view.getTag();
			fechaSeleccionada=date_month_year;
			//dia seleccionado
			diaSeleccionado=date_month_year.substring(0,2);
			//mes seleccionado
			if (date_month_year.contains("January")){
				mesSeleccionado="01";
			}else if (date_month_year.contains("February")){
					mesSeleccionado="02";
			}else if (date_month_year.contains("March")){
				mesSeleccionado="03";
			}else if (date_month_year.contains("April")){
				mesSeleccionado="04";
			}else if (date_month_year.contains("May")){
				mesSeleccionado="05";
			}else if (date_month_year.contains("June")){
				mesSeleccionado="06";
			}else if (date_month_year.contains("July")){
				mesSeleccionado="07";
			}else if (date_month_year.contains("August")){
				mesSeleccionado="08";
			}else if (date_month_year.contains("September")){
				mesSeleccionado="09";
			}else if (date_month_year.contains("October")){
				mesSeleccionado="10";
			}else if (date_month_year.contains("November")){
				mesSeleccionado="11";
			}else if (date_month_year.contains("December")){
				mesSeleccionado="12";
			}
					
			//año seleccionado
			añoSeleccionado=date_month_year.substring(date_month_year.length()-4,date_month_year.length() );
			
			
		    Intent intent = new Intent(MyCalendarActivity.this, Noticia.class); 
		    startActivity(intent); 
		   
		    //IncluirDatos(date_month_year);
			Log.e("Selected date", date_month_year);
			try {
				Date parsedDate = dateFormatter.parse(date_month_year);
				Log.d(tag, "Parsed Date: " + parsedDate.toString());

			} catch (ParseException e) {
				e.printStackTrace();
			}
		}


		public int getCurrentDayOfMonth() {
			return currentDayOfMonth;
		}

		public void setCurrentDayOfMonth(int currentDayOfMonth) {
			this.currentDayOfMonth = currentDayOfMonth;
		}

		public void setCurrentWeekDay(int currentWeekDay) {
			this.currentWeekDay = currentWeekDay;
		}

		public int getCurrentWeekDay() {
			return currentWeekDay;
		}
	    
	}
	
}
	
